package com.atguigu.szdz.dcsyl.common.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream; // 导入
import java.io.IOException;
import java.io.InputStream; // 导入
import java.io.InputStreamReader; // 导入
import java.nio.charset.StandardCharsets; // 导入
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class LasParser {

    /**
     * [核心方法] 从任何输入流解析 .las 数据
     * @param inputStream 文件输入流
     * @return 解析后的 LasFile 对象
     * @throws IOException 如果读取流失败
     */
    public LasFile parse(InputStream inputStream) throws IOException {
        LasFile lasFile = new LasFile();
        String currentSection = "";
        StringBuilder otherInfoBuilder = new StringBuilder();

        // 使用 InputStreamReader 来读取流，并指定UTF-8编码以提高兼容性
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String trimmedLine = line.trim();
                if (trimmedLine.isEmpty() || trimmedLine.startsWith("#")) {
                    if (currentSection.toUpperCase().startsWith("OTHER")) {
                        otherInfoBuilder.append(line).append("\n");
                    }
                    continue;
                }

                if (trimmedLine.startsWith("~")) {
                    String sectionHeader = trimmedLine.substring(1).trim();
                    currentSection = sectionHeader.split("\\s+")[0].toUpperCase();

                    if (currentSection.startsWith("OTHER")) {
                        lasFile.setOtherInfo(otherInfoBuilder.toString());
                    }
                    if (currentSection.equalsIgnoreCase("A")) {
                        for (LasFile.CurveInfo curve : lasFile.getCurveInfoList()) {
                            lasFile.getCurveData().put(curve.mnemonic, new ArrayList<>());
                        }
                    }
                    continue;
                }

                // ... 内部解析逻辑完全不变 ...
                switch (currentSection) {
                    case "VERSION":
                        parseKeyValue(line, lasFile.getVersionInfo());
                        break;
                    case "WELL":
                        parseMnemonicLine(line, lasFile.getWellInfo());
                        break;
                    case "CURVE":
                        parseCurveLine(line, lasFile.getCurveInfoList());
                        break;
                    case "PARAMETER":
                        parseMnemonicLine(line, lasFile.getParameterInfo());
                        break;
                    case "OTHER":
                        otherInfoBuilder.append(line).append("\n");
                        break;
                    case "A":
                        parseDataLine(line, lasFile);
                        break;
                }
            }
        }
        return lasFile;
    }

    /**
     * 重载方法：保持对 File 对象的兼容性
     * @param file 要解析的 File 对象
     * @return 解析后的 LasFile 对象
     * @throws IOException 如果文件读取失败
     */
    public LasFile parse(File file) throws IOException {
        try (InputStream is = new FileInputStream(file)) {
            return parse(is); // 调用核心的 InputStream 方法
        }
    }

    /**
     * 重载方法：保持对文件路径字符串的兼容性
     * @param filePath 文件的路径字符串
     * @return 解析后的 LasFile 对象
     * @throws IOException 如果文件读取失败
     */
    public LasFile parse(String filePath) throws IOException {
        return parse(new File(filePath));
    }


    // ===============================================================
    // 以下所有私有辅助方法 (private helper methods) 保持完全不变
    // ===============================================================

    private void parseMnemonicLine(String line, java.util.Map<String, LasFile.WellParameter> map) {
        int colonIndex = line.indexOf(':');
        if (colonIndex == -1) return;
        String description = line.substring(colonIndex + 1).trim();
        String mainPart = line.substring(0, colonIndex);
        int dotIndex = mainPart.indexOf('.');
        if (dotIndex == -1) return;
        String mnemonic = mainPart.substring(0, dotIndex).trim();
        String remainder = mainPart.substring(dotIndex + 1).trim();
        String[] parts = remainder.split("\\s+");
        String unit = "";
        String value = "";
        if (parts.length == 1 && !parts[0].isEmpty()) {
            unit = "";
            value = parts[0];
        } else if (parts.length >= 2) {
            unit = parts[0];
            value = String.join(" ", Arrays.copyOfRange(parts, 1, parts.length));
        }
        LasFile.WellParameter param = new LasFile.WellParameter();
        param.mnemonic = mnemonic;
        param.unit = unit;
        param.value = value;
        param.description = description;
        map.put(mnemonic, param);
    }

    private void parseCurveLine(String line, List<LasFile.CurveInfo> list) {
        int colonIndex = line.indexOf(":");
        if (colonIndex == -1) return;
        String description = line.substring(colonIndex + 1).trim();
        String mainPart = line.substring(0, colonIndex);
        int dotIndex = mainPart.indexOf('.');
        if (dotIndex == -1) {
            String[] parts = mainPart.trim().split("\\s+", 2);
            LasFile.CurveInfo curveInfo = new LasFile.CurveInfo();
            curveInfo.mnemonic = parts[0];
            curveInfo.unit = "";
            curveInfo.apiCode = (parts.length > 1) ? parts[1].trim() : "";
            curveInfo.description = description;
            list.add(curveInfo);
            return;
        }
        String mnemonic = mainPart.substring(0, dotIndex).trim();
        String remainder = mainPart.substring(dotIndex + 1).trim();
        String[] parts = remainder.split("\\s+");
        String unit = "";
        String apiCode = "";
        if (parts.length > 0 && !parts[0].isEmpty()) {
            unit = parts[0];
        }
        if (parts.length > 1) {
            apiCode = parts[1];
        }
        LasFile.CurveInfo curveInfo = new LasFile.CurveInfo();
        curveInfo.mnemonic = mnemonic;
        curveInfo.unit = unit;
        curveInfo.apiCode = apiCode;
        curveInfo.description = description;
        list.add(curveInfo);
    }

    private void parseKeyValue(String line, java.util.Map<String, String> map) {
        int colonIndex = line.indexOf(':');
        if (colonIndex == -1) return;
        String keyPart = line.substring(0, colonIndex);
        String valuePart = line.substring(colonIndex + 1).trim();
        int dotIndex = keyPart.indexOf('.');
        if (dotIndex == -1) return;
        String key = keyPart.substring(0, dotIndex).trim();
        map.put(key, valuePart);
    }

    private void parseDataLine(String line, LasFile lasFile) {
        String[] values = line.trim().split("\\s+");
        List<LasFile.CurveInfo> curves = lasFile.getCurveInfoList();
        if (values.length != curves.size()) {
            return;
        }
        for (int i = 0; i < values.length; i++) {
            String curveMnemonic = curves.get(i).mnemonic;
            try {
                double value = Double.parseDouble(values[i]);
                lasFile.getCurveData().get(curveMnemonic).add(value);
            } catch (NumberFormatException e) {
                lasFile.getCurveData().get(curveMnemonic).add(Double.NaN);
            }
        }
    }
}